<?php

namespace app\backstage\controller;


use app\model\TaskComplete as model;
use app\model\FreshAdminUser;
use app\model\FreshAdminAuthGroupAccess;
use app\model\TaskRecord;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\util\ReturnCode;
use app\util\Tools;
use think\Db;
use think\Exception;

class TaskComplete extends Base {

    public function index(){
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['status'])){
                $query->where('u.status', intval($postData['status']));
            }
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('u.title',  'like','%'.$postData['keyword'].'%');
            }


            $platformID = $this->userPlatform();
            if($platformID == 0){
                if(isset($postData['platformID']) && $postData['platformID']){
                    $query->where('u.platformID', $postData['platformID']);
                }
            }else{
                $query->where('u.platformID', $platformID);
            }

            if(isset($postData['beginTime']) && $postData['beginTime']){
                $query->where('u.addTime', '>=', strtotime($postData['beginTime']));
            }
            if(isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', '<=', $endTime);
            }
            if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', [ '>=' , strtotime($postData['beginTime'])],['<=', $endTime], 'and');
            }

        };



        $list = model::alias('u')
        ->field('u.*,t.title as taskTitle,a.username as checkManagerName,p.name as platformName,a1.username as addUserName, uu.mobile')
        ->join('user uu', 'uu.userID=u.userID', 'left')
        ->join('task t', 't.taskID=u.taskID', 'left')
        ->join('fresh_admin_user a', 'a.id=u.checkMid', 'left')
        ->join('fresh_admin_user a1', 'a1.id=u.opMid', 'left')
        ->join('platform p', 'p.id=u.platformID', 'left')
        ->where($where)
        ->order('sort desc,addTime desc')
        ->limit(( $page - 1 ) * $size , $size)
        ->select();
        if($list){
            $list->append(['statusText']);
        }

        foreach($list as $key => $var){
            $var->data('checkTimeStr', $var['checkTime'] ? date("Y-m-d H:i:s", $var['checkTime']) : '');
        }

        $count =   model::alias('u')
        ->where($where)
        ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }



    public function add(){

        $postData = $this->request->post();


        if(!isset($postData['taskID']) || empty($postData['taskID'])){
            return $this->buildFailed(ReturnCode::INVALID, '请选择任务');
        }
        if(!isset($postData['resultImg']) || empty($postData['resultImg'])){
            return $this->buildFailed(ReturnCode::INVALID, '请任务截图');
        }
        if(!isset($postData['userID']) || empty($postData['userID'])){
            return $this->buildFailed(ReturnCode::INVALID, '请选择用户');
        }
        $userPlatform = $this->userPlatform();
        if(!$userPlatform)  return $this->buildFailed(ReturnCode::INVALID, '必须由操作组来完成提交[-1]');
        if(!$this->userInfo['isOp'])  return $this->buildFailed(ReturnCode::INVALID, '必须由操作组来完成提交');
        $task = Db::name('task')->where('taskID', $postData['taskID'])->find();
        if($task['status'] != 1)  return $this->buildFailed(ReturnCode::INVALID, '任务未上线');
        if($task['isUp'] == 2)  return $this->buildFailed(ReturnCode::INVALID, '任务已下架');
        $user_allot = Db::name('user_allot')->where(['userID' => $postData['userID'], 'opMid' => $this->userInfo['id']])->find();
        if(!$user_allot['id']) return $this->buildFailed(ReturnCode::INVALID, '该账号不属于您');
        $data = [
            'taskID' => $postData['taskID'],
            'userID' => $postData['userID'],
            'opMid' => $this->userInfo['id'],
            'addTime' => time(),
            'status' => -1,
            'platformID' => $userPlatform,
            'remark' => isset($postData['remark']) ? $postData['remark'] : '',
            'resultImg' => $postData['resultImg'],
        ];


        $res = model::create($data);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }

    }



    public function setStatus(){
        $postData = $this->request->post();
        if(!isset($postData['id']) || empty($postData['id'])){
            return $this->buildFailed(ReturnCode::INVALID, 'ID为空');
        }
        if(!isset($postData['status']) || empty($postData['status'])){
            return $this->buildFailed(ReturnCode::INVALID, '状态值为空');
        }
        if($postData['status'] < 1 || $postData['status'] >= 9){
            return $this->buildFailed(ReturnCode::INVALID, '无效状态值');
        }

        Db::startTrans();
        try {

            $task = model::get($postData['id']);
            if(empty($task)){
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '任务审核记录不存在');
            }
            $taskData = \app\model\Task::get(['taskID' => $task['taskID']]);
            if($taskData->num<1)     return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '任务暂无剩余次数');
            $userPlatform = $this->userPlatform();
            if(!$userPlatform)  return $this->buildFailed(ReturnCode::INVALID, '必须由操作组来完成提交[-1]');
            $userPlatform = $this->userPlatform();
            if($userPlatform &&  $task->platformID != $userPlatform){
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能编辑其他平台任务');
            }
            if($task['status'] != -1)   return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '记录已审核');
            $res = model::where('id', $postData['id'])->update(['status' => $postData['status'], 'checkMid' => $this->userInfo['id'], 'checkTime'=>time(), 'updateTime' =>time()]);
            if ($res === false) {
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
            } else {
                if($postData['status'] == 9){
                    $flag = TaskRecord::where('taskID', $postData['taskID'])->update(['status' => 2, 'remark' => '任务取消取消分配', 'updateTime' => time()]);
                    if(!$flag) throw new Exception('任务取消失败');
                }
                if($postData['status'] == 1){
                    $taskData->num = $taskData->num -1;
                    $taskData->completeNUm = $taskData->completeNUm +1;
                    $flag = $taskData->save();
                    if(!$flag) throw new Exception('更新任务失败！');
                }
            }

            Db::commit();
            return $this->buildSuccess([]);
        }catch (Exception $e){
            Db::rollback();
            return Tools::buildReturn(ReturnCode::INVALID, $e->getMessage());
        }


    }









}

?>
